package com.ja.openchat.ui.found;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;

import com.allen.library.SuperButton;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.dueeeke.videoplayer.player.VideoView;
import com.google.gson.JsonObject;
import com.gyf.immersionbar.ImmersionBar;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.ui.chat.ForwardActivity;
import com.ja.openchat.ui.chat.GoChatPicEditActivity;
import com.ja.openchat.ui.chat.MessageViewModel;
import com.ja.openchat.ui.me.MyAlbumFragment;
import com.ja.openchat.ui.tiktok.TikTokController;
import com.ja.openchat.ui.tiktok.TikTokRenderViewFactory;
import com.ja.openchat.views.BottomSheetBar;
import com.ja.openchat.views.InputAwareLayout;
import com.ja.openchat.views.NoScrollVerticalViewPager;
import com.ja.openchat.views.UserAvatarView;
import com.ja.openchat.views.Utils;
import com.ja.openchat.views.VerticalViewPager;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.nanchen.compresshelper.CompressHelper;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider;
import com.vachel.editor.PictureEditActivity;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.circle.BlogInfo;
import com.zy.openchat.core.model.circle.BlogListInfo;
import com.zy.openchat.core.model.circle.BlogReplyInfo;
import com.zy.openchat.core.model.circle.BlogUserInfo;
import com.zy.openchat.core.model.circle.CircleVisibleType;
import com.zy.openchat.core.model.circle.InputBlogIdType;
import com.zy.openchat.core.model.circle.OnReplyScollEvent;
import com.zy.openchat.core.model.circle.RefreshBlogEvent;
import com.zy.openchat.core.model.circle.RefreshBlogReplyEvent;
import com.zy.openchat.core.model.file.FileInfo;
import com.zy.openchat.core.model.file.FileTaskInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.photo.PhotoInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.core.model.video.UploadMedioInfo;
import com.zy.openchat.core.model.video.VideoInfo;
import com.zy.openchat.util.Common;
import com.zy.openchat.util.SingleMediaScanner;
import com.zy.openchat.util.glide.GlideApp;
import com.zy.openchat.util.share.GoShare;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class CircleVerticalActivity extends JaBaseActivity implements OnCircleRemarkListener{

    public static void start(Context context,int circleType,ArrayList<BlogInfo> blogInfos,int index,int childIndex,int currentPage){
        Intent intent = new Intent(context,CircleVerticalActivity.class);
        intent.putExtra("blogs",blogInfos);
        intent.putExtra("index",index);
        intent.putExtra("blogType",circleType);
        intent.putExtra("childIndex",childIndex);
        intent.putExtra("currentPage",currentPage);
        context.startActivity(intent);
    }

    @BindView(R.id.vvp)
    NoScrollVerticalViewPager mViewPager;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.mainTitleLayout)
    View mainTitleLayout;
    @BindView(R.id.rootLinearLayout)
    InputAwareLayout rootLinearLayout;
    @BindView(R.id.headerImageView)
    UserAvatarView headerImageView;
    @BindView(R.id.userNameText)
    TextView userNameText;
    @BindView(R.id.focus_btn)
    SuperButton focus_btn;

    private VideoView mVideoView;
    private Tiktok2Adapter mTiktok2Adapter;
    private TikTokController mController;
    private List<BlogInfo> mVideoList = new ArrayList<>();
    private List<Integer> mBlogIndexs = new ArrayList<>();
    private int mCurPos;
    private int mType = 0;
    @Override
    public void initData() {
        ArrayList<BlogInfo> data = null;
        int index = 0;
        int childIndex = 0;
        if(getIntent()!=null){
            mType = getIntent().getIntExtra("blogType",0);
            data = (ArrayList<BlogInfo>) getIntent().getSerializableExtra("blogs");
            index = getIntent().getIntExtra("index",0);
            childIndex = getIntent().getIntExtra("childIndex",0);
            mCurrentPage = getIntent().getIntExtra("currentPage",1);
        }
        if(Common.isEmpty(data)){
            finish();
            return;
        }
        int targetIndex = addData(data,true,index,childIndex);
        initSmartRefresh(targetIndex);
        initViewPager();
        initVideoView();

        mViewPager.post(new Runnable() {
            @Override
            public void run() {
                if(targetIndex == 0){
                    startPlay(targetIndex);
                }else{
                    mViewPager.setCurrentItem(targetIndex,false);
                }
            }
        });


    }

    private int addData(ArrayList<BlogInfo> data,boolean isSetCus,int index,int childIndex){
        int targetIndex = 0;
        int position = 0;
        int length = data.size();
        for(int i =0 ;i<length;i++){
            BlogInfo blog = data.get(i);
            if(blog.content!=null&&!Common.isEmpty(blog.content.photos)){
                int childLength = blog.content.photos.size();
                for(int j = 0;j<childLength;j++){
                    PhotoInfo photoInfo = blog.content.photos.get(j);
                    if(isSetCus&&i == index&&childIndex == j){
                        targetIndex = position;
                    }
                    mVideoList.add(blog);
                    mBlogIndexs.add(j);
                    position++;
                }
            }else{
                if(isSetCus&&i == index){
                    targetIndex = position;
                }
                position++;
                mVideoList.add(blog);
                mBlogIndexs.add(0);
            }
        }
        return targetIndex;
    }

    private int mCurrentPage = 1;
    private void initSmartRefresh(final int targetIndex){
        ClassicsFooter classicsFooter = new ClassicsFooter(this);
        classicsFooter.setDrawableProgressSize(21);
        classicsFooter.setTextSizeTitle(14);
        classicsFooter.setAccentColor(Color.parseColor("#ffffff"));
        classicsFooter.setFinishDuration(1);
        smartRefreshLayout.setRefreshFooter(classicsFooter);
        ClassicsHeader.REFRESH_HEADER_PULLING = getString(R.string.down_to_exit);
        ClassicsHeader.REFRESH_HEADER_REFRESHING = getString(R.string.exiting_text);
        ClassicsHeader.REFRESH_HEADER_RELEASE = getString(R.string.release_to_exit);
        ClassicsHeader classicsHeader = new ClassicsHeader(this);
        classicsHeader.setEnableLastTime(false);
        classicsHeader.setTextSizeTitle(14);
        classicsHeader.setDrawableProgressSize(21);
        classicsHeader.setTextSizeTime(10);
        classicsHeader.setFinishDuration(1);
        classicsHeader.setAccentColor(Color.parseColor("#ffffff"));
        smartRefreshLayout.setRefreshHeader(classicsHeader);
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                mCurrentPage++;
                requestData(mCurrentPage);
            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
//                mCurrentPage = 1;
//                requestData(mCurrentPage);
                finish();
            }
        });
        smartRefreshLayout.setScrollBoundaryDecider(new ScrollBoundaryDecider() {
            @Override
            public boolean canRefresh(View content) {
                return mVideoList.size()==1||mCurPos == targetIndex;
            }

            @Override
            public boolean canLoadMore(View content) {
                return mVideoList.size()==1||mCurPos == mVideoList.size()-1;
            }
        });
    }

    protected void requestData(int page) {
        TelegramManager.getTelegramManager().getCircleHistory(this, new CircleVisibleType(mType,null), getLastBlogId(page) ,20, new TgResultBlock<BlogListInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, BlogListInfo obj) {
                if(obj!=null&&obj.blogs!=null){
                    if(page == 1){
                        smartRefreshLayout.finishRefresh();
                        mVideoList.clear();
                        mBlogIndexs.clear();
                        addData(obj.blogs,false,0,0);
                        smartRefreshLayout.setNoMoreData(Common.isEmpty(obj.blogs));
                    }else{
                        if(Common.isEmpty(obj.blogs)){
                            smartRefreshLayout.finishLoadMoreWithNoMoreData();
                        }else{
                            smartRefreshLayout.finishLoadMore();
                        }

                        addData(obj.blogs,false,0,0);
                    }
                    mTiktok2Adapter.notifyDataSetChanged();
                }else{
                    smartRefreshLayout.finishLoadMoreWithNoMoreData();
                }
            }


            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    @OnClick({R.id.ivBackBtn,R.id.headerImageView,R.id.focus_btn})
    void onClick(View view) {
        switch (view.getId()){
            case R.id.ivBackBtn:
                onBackPressed();
                break;
            case R.id.headerImageView:
            case R.id.focus_btn:
                if(mCurrentViewHolder!=null){
                    mCurrentViewHolder.mTikTokView.onClick(view);
                }
                break;
        }
    }

    private long getLastBlogId(int page){
        if(page==1){
            return 0;
        }else{
            return mVideoList.get(mVideoList.size()-1).id;
        }
    }
    private void initVideoView() {
        mVideoView = new VideoView(this);
        mVideoView.setLooping(true);
        //以下只能二选一，看你的需求
        mVideoView.setRenderViewFactory(TikTokRenderViewFactory.create());
//        mVideoView.setScreenScaleType(VideoView.SCREEN_SCALE_CENTER_CROP);

        mController = new TikTokController(this);
        mController.addDefaultControlComponent("预览");
        mVideoView.setVideoController(mController);

    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if(mVideoView!=null&&mVideoView.getVideoSize()!=null){
            mVideoView.onVideoSizeChanged(mVideoView.getVideoSize()[0],mVideoView.getVideoSize()[1]);
        }
        mViewPager.setNoScroll(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE);
    }

    private void initViewPager() {
        int statusHeight = ImmersionBar.getStatusBarHeight(this);
        ((ViewGroup.MarginLayoutParams)mainTitleLayout.getLayoutParams()).topMargin = statusHeight;
        mViewPager.setOffscreenPageLimit(4);
        mTiktok2Adapter = new Tiktok2Adapter(mVideoList,mBlogIndexs,statusHeight);
        mViewPager.setAdapter(mTiktok2Adapter);
        mViewPager.setOverScrollMode(View.OVER_SCROLL_NEVER);
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

            private int mCurItem;

            /**
             * VerticalViewPager是否反向滑动
             */
            private boolean mIsReverseScroll;

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                if (position == mCurItem) {
                    return;
                }
                mIsReverseScroll = position < mCurItem;
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if (position == mCurPos) return;
                startPlay(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
                if (state == VerticalViewPager.SCROLL_STATE_DRAGGING) {
                    mCurItem = mViewPager.getCurrentItem();
                }
            }
        });
    }

    private void startPlay(int position) {
        int count = mViewPager.getChildCount();
        for (int i = 0; i < count; i ++) {
            View itemView = mViewPager.getChildAt(i);
            Tiktok2Adapter.ViewHolder viewHolder = (Tiktok2Adapter.ViewHolder) itemView.getTag();
            if (viewHolder.mPosition == position) {
                BlogInfo blogInfo = mVideoList.get(position);
                if(mCurrentViewHolder == viewHolder&&blogInfo.content!=null&&blogInfo.content.video!=null){
                    long playPosition = mVideoView.getCurrentPosition();
                    if(!mVideoView.isPlaying()&&playPosition>0){
                        mVideoView.start();
                        mVideoView.seekTo(playPosition);
                    }else if(!mVideoView.isPlaying()){
                        mVideoView.setUrl(blogInfo.content.video.localVideoPath());
                        mVideoView.start();
                    }
                    return;
                }
                initCurrentView(viewHolder);
                mCurPos = position;
                mVideoView.release();
                Utils.removeViewFormParent(mVideoView);

                if(blogInfo.content==null||blogInfo.content.video==null){
                    break;
                }
                String playUrl = blogInfo.content.video.localVideoPath();
                mVideoView.setUrl(playUrl);
                mController.addControlComponent(viewHolder.mTikTokView, true);
                viewHolder.mPlayerContainer.addView(mVideoView, 0);
                mVideoView.start();
                break;
            }
        }
    }
    private HashMap<Long, BlogUserInfo> blogUserInfoHashMap = new HashMap<>();
    private BlogInfo mCurrentBlogInfo = null;
    private Tiktok2Adapter.ViewHolder mCurrentViewHolder = null;
    private boolean isDetailMode = false;
    private void initCurrentView(final Tiktok2Adapter.ViewHolder viewHolder){
        if(viewHolder == null){
            return;
        }
        mCurrentViewHolder = viewHolder;
        mCurrentBlogInfo = mVideoList.get(viewHolder.mPosition);
        final BlogInfo blogInfo = mCurrentBlogInfo;
        viewHolder.mTikTokView.setListener(new OnCircleVerticalViewHandleListener() {
            @Override
            public void onFocusClick() {
                invokeFocusClick(blogInfo,viewHolder);
            }

            @Override
            public void onUserHeadCick() {
                Bundle bundle = new Bundle();
                bundle.putLong("userId", blogInfo.user_id);
                viewModel.startContainerActivity(MyAlbumFragment.class.getCanonicalName(), bundle);
            }

            @Override
            public void onMoreClick() {
                showMoreDialog(blogInfo,mBlogIndexs.get(viewHolder.mPosition));
            }

            @Override
            public BlogUserInfo requestBlogUserInfo(long userId) {
                return getBlogUserInfo(userId,blogInfo,viewHolder);
            }

            @Override
            public void onLikeClick() {
                invokeLike(blogInfo,viewHolder);
            }

            @Override
            public void onCommentClick() {
//                CircleDetailActivity.startDetail(CircleVerticalActivity.this, blogInfo.id, 1);
                invokeComment(blogInfo,viewHolder);
            }

            @Override
            public void onMoneyClick() {

            }

            @Override
            public boolean isDetailTextMode() {
                return isDetailMode;
            }

            @Override
            public void setDetailMode(boolean isDetail) {
                isDetailMode = isDetail;
                viewHolder.mTikTokView.setData(blogInfo,mBlogIndexs.get(viewHolder.mPosition));
            }
        });
        viewHolder.mTikTokView.setData(blogInfo,mBlogIndexs.get(viewHolder.mPosition));
        setUserView(blogInfo,viewHolder);
    }

    private void setUserView(BlogInfo blogInfo,final Tiktok2Adapter.ViewHolder viewHolder){
        UserInfo userInfo = UserInfo.getUserInfo(blogInfo.user_id);
        if (userInfo != null) {
            if (userInfo.profile_photo != null && !userInfo.profile_photo.isSmallPhotoDownloaded()) {
                blogInfo.isAvaterDownloaded = false;
            } else {
                blogInfo.isAvaterDownloaded = true;
            }
            userNameText.setText(userInfo.displayName());
            headerImageView.showUser(userInfo);
        } else {
            headerImageView.showDefault();
            userNameText.setText("");
            blogInfo.isAvaterDownloaded = false;
            TelegramManager.getTelegramManager().getUserSimpleInfo(blogInfo.user_id);
        }
        if (blogInfo.user_id == UserInfo.getUserInfo().id) {
            focus_btn.setVisibility(View.GONE);
        }else {
            BlogUserInfo blogUserInfo = getBlogUserInfo(blogInfo.user_id,blogInfo,viewHolder);
            if (blogUserInfo != null) {
                focus_btn.setVisibility(View.VISIBLE);
                if (blogUserInfo.followed) {
                    focus_btn.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                    focus_btn.setTextColor(getResources().getColor(R.color.me_nick_name_color_text_sub));
                    focus_btn.setShapeStrokeColor(getResources().getColor(R.color.color_f5f9fa));
                    focus_btn.setShapeSolidColor(getResources().getColor(R.color.color_f5f9fa)).setUseShape();
                    focus_btn.setText(getString(R.string.focused_text));
                } else {
                    focus_btn.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.mipmap.follow_add), null, null, null);
                    focus_btn.setText(getString(R.string.unfocus_text));
                    focus_btn.setTextColor(getResources().getColor(R.color.login_btn_bg_color));
                    focus_btn.setShapeStrokeColor(getResources().getColor(R.color.login_btn_bg_color));
                    focus_btn.setShapeSolidColor(getResources().getColor(R.color.white)).setUseShape();

                }
            } else {
                focus_btn.setVisibility(View.GONE);
            }

        }
    }

    private BottomSheetBar mBottomSheetBar;
    private void invokeComment(final BlogInfo blogInfo ,final Tiktok2Adapter.ViewHolder viewHolder){
        new XPopup.Builder(this)
                .moveUpToKeyboard(false)
                .isDestroyOnDismiss(true)
                .asCustom(new CircleCommentDialog(this, viewModel, blogInfo, new OnCircleCommentListener() {
                    @Override
                    public void onCircleComment(InputBlogIdType blogIdType, String hint, View view) {
                        showRemarkBar(blogIdType,hint,view);
                    }
                }))
                .show();
    }

    @Override
    public void showRemarkBar(InputBlogIdType blogIdType,String hint, View view){
        if(mBottomSheetBar==null){
            mBottomSheetBar = BottomSheetBar.delegation(this,rootLinearLayout);
            mBottomSheetBar.setCallback(new BottomSheetBar.OnBottomCallback() {
                @Override
                public void onShow(int[] inputViewCoordinatesOnScreen) {
                    EventBus.getDefault().post(new OnReplyScollEvent(inputViewCoordinatesOnScreen));
                }

                @Override
                public void onClickSend(InputBlogIdType targetId, String content) {
                    showProgress();
                    TelegramManager.getTelegramManager().commentBlog(CircleVerticalActivity.this, targetId, content, new TgResultBlock<TgResponse>() {
                        @Override
                        public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                            hideProgress();
                            if(obj!=null){
                                if(obj.ok){
                                    mBottomSheetBar.clean();
                                    EventBus.getDefault().post(new RefreshBlogReplyEvent());
                                }else{
                                    showErrorTip(obj.errString);
                                }
                            }else{
                                showErrorTip(getString(R.string.request_error));
                            }
                        }

                        @Override
                        public void onTimeout(Map<String, Object> request) {
                            hideProgress();
                            showErrorTip(getString(R.string.request_error));
                        }
                    });
                }
            });
        }
        mBottomSheetBar.setTargetId(blogIdType);
        mBottomSheetBar.show(hint,view);
    }

    private void invokeLike(final BlogInfo blogInfo ,final Tiktok2Adapter.ViewHolder viewHolder) {
        if(blogInfo==null||viewHolder==null){
            return;
        }
        InputBlogIdType inputBlogIdType = new InputBlogIdType(true, blogInfo.id);
        final boolean isLike = !blogInfo.liked;
        final int position = viewHolder.mPosition;
        showProgress();
        TelegramManager.getTelegramManager().likeBlog(this, inputBlogIdType, isLike, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (obj != null) {
                    if (obj.ok) {
                        blogInfo.liked = isLike;
                        blogInfo.like_count = isLike ? blogInfo.like_count + 1 : blogInfo.like_count - 1;
                        viewHolder.mTikTokView.setData(blogInfo,mBlogIndexs.get(position));
                        EventBus.getDefault().post(TgEvent.event(TelegramManager.EUser_TgEvent.ECircle_Like_Update, blogInfo));
                        TelegramManager.getTelegramManager().getCircleUnreadCount();
                    } else {
                        showErrorTip(obj.errString);
                    }
                } else {
                    showErrorTip(getString(R.string.request_error));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private void invokeFocusClick(final BlogInfo blogInfo,final Tiktok2Adapter.ViewHolder viewHolder){
        if(blogInfo==null||viewHolder==null){
            return;
        }
        BlogUserInfo blogUserInfo = getBlogUserInfo(blogInfo.user_id,blogInfo,viewHolder);
        if (blogUserInfo == null) {
            return;
        }
        boolean followed = !blogUserInfo.followed;
        if (followed) {
            actionFollow(blogInfo, followed,viewHolder);
        } else {
            new XPopup.Builder(this).autoDismiss(true).asConfirm(
                    getString(R.string.dialog_title_tip)
                    , getString(R.string.unfollow_the_user_text)
                    , getString(R.string.cancle_text)
                    , getString(R.string.ok_text), new OnConfirmListener() {
                @Override
                public void onConfirm() {
                    actionFollow(blogInfo, followed,viewHolder);
                }
            }, new OnCancelListener() {
                @Override
                public void onCancel() {

                }
            }, false).show();
        }
    }

    private void actionFollow(final BlogInfo blogInfo, boolean followed,final Tiktok2Adapter.ViewHolder viewHolder) {
        showProgress();
        TelegramManager.getTelegramManager().followBlog(this, blogInfo.user_id, followed, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (obj != null) {
                    if (obj.ok) {
                        BlogUserInfo blogUserInfo = getBlogUserInfo(blogInfo.user_id,blogInfo,viewHolder);
                        if (blogUserInfo != null) {
                            blogUserInfo.followed = followed;
                            if(mCurrentViewHolder == viewHolder){
                                setUserView(blogInfo,viewHolder);
                            }
                            EventBus.getDefault().post(TgEvent.event(TelegramManager.EUser_TgEvent.ECircle_Follow_Update, blogUserInfo));
                        }
                    } else {
                        showErrorTip(obj.errString);
                    }
                } else {
                    showErrorTip(getString(R.string.request_error));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private void showMoreDialog(BlogInfo blogInfo,int childIndex){
        if(blogInfo==null){
            return;
        }
        Object mediaInfo = null;
        if(blogInfo.content!=null){
            if(!Common.isEmpty(blogInfo.content.photos)){
                mediaInfo = blogInfo.content.photos.get(childIndex);
            }else{
                mediaInfo = blogInfo.content.video;
            }
        }
        if(mediaInfo==null){
            return;
        }
        final String[] popuTitles;
        if(mediaInfo instanceof PhotoInfo){
            popuTitles = new String[]{getString(R.string.save_album), getString(R.string.share_text),getString(R.string.edit_text),getString(R.string.forward_text),getString(R.string.collect_text)};
        }else{
            popuTitles = new String[]{getString(R.string.save_album), getString(R.string.share_text),getString(R.string.forward_text),getString(R.string.collect_text)};
        }
        final Object messageInfo = mediaInfo;
        new XPopup.Builder(CircleVerticalActivity.this).asBottomList(null, popuTitles, new OnSelectListener() {
            @Override
            public void onSelect(int position, String text) {
                String filePath = null;
                boolean isDownloadCompleted = false;
                if(messageInfo instanceof PhotoInfo){
                    PhotoInfo photoInfo = (PhotoInfo) messageInfo;
                    if(photoInfo.isPhotoDownloaded()){
                        filePath = photoInfo.getPhotoImagePath();
                        isDownloadCompleted = true;
                    }
                }else{
                    VideoInfo videoInfo = (VideoInfo) messageInfo;
                    if(videoInfo.isVideoDownloaded()){
                        filePath = videoInfo.localVideoPath();
                    }
                    isDownloadCompleted = videoInfo.isVideoDownloadComplete();
                }
                if(TextUtils.isEmpty(filePath)){
                    ToastUtils.showShort(getString(R.string.downloading_try_again));
                    return;
                }
                if(position == 1){
                    if(!isDownloadCompleted){
                        ToastUtils.showShort(getString(R.string.downloading_try_again));
                        return;
                    }
                    new GoShare.FShareBuilder(CircleVerticalActivity.this, App.getInstanse().getPackageName() + ".utilcode.fileprovider")
                            .setFilePath(filePath)
                            .setShareSubject(getResources().getString(R.string.app_name))
                            .build()
                            .shareByCustom();

                }else if(position == 0){
                    if(!isDownloadCompleted){
                        ToastUtils.showShort(getString(R.string.downloading_try_again));
                        return;
                    }
                    if(messageInfo instanceof PhotoInfo){
                        try {
                            MediaStore.Images.Media.insertImage(getContentResolver(), filePath, getResources().getString(R.string.app_name), getResources().getString(R.string.app_name));
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        new SingleMediaScanner(getApplicationContext(), filePath, new SingleMediaScanner.ScanListener() {
                            @Override
                            public void onScanFinish() {
                                ToastUtils.showShort(getString(R.string.save_album_success));
                            }
                        });

                    }else{
                        try {
                            PreviewCircleMediaActivity.saveVideo(CircleVerticalActivity.this,new File(filePath));
//                                        insertVideo(filePath,PreviewMediaActivity.this);
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                    }
                }else if((position == 2&&popuTitles.length==5)){
                    Intent intent = new Intent(CircleVerticalActivity.this, GoChatPicEditActivity.class);
                    intent.putExtra(PictureEditActivity.EXTRA_IMAGE_URI, Uri.fromFile(new File(filePath)));
                    intent.putExtra(PictureEditActivity.EXTRA_TYPE,1);
                    CircleVerticalActivity.this.startActivity(intent);
                }else if((position == 2&&popuTitles.length==4)||(position == 3&&popuTitles.length==5)){
                    Intent intent = new Intent(CircleVerticalActivity.this, ForwardActivity.class);
                    if(messageInfo instanceof PhotoInfo){
                        intent.putExtra(ForwardActivity.BUNDLE_REMOTE_PHOTO,(PhotoInfo)messageInfo);
                    }else if(messageInfo instanceof VideoInfo){
                        intent.putExtra(ForwardActivity.BUNDLE_REMOTE_VIDEO,(VideoInfo)messageInfo);
                    }else{
                        intent.putExtra(ForwardActivity.BUNDLE_OUTER_PATH,filePath);
                    }

                    CircleVerticalActivity.this.startActivity(intent);
                }else if((position == 3&&popuTitles.length==4)||(position == 4&&popuTitles.length==5)){
                    showProgress();
                    final String localPath = filePath;
                    TelegramManager.getTelegramManager().createPrivateChat(CircleVerticalActivity.this, UserInfo.getUserInfo().id, new TgResultBlock<ChatInfo>() {
                        @Override
                        public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                            if (obj != null) {
                                sendMedia(messageInfo,localPath,obj);
                            }else{
                                hideProgress();
                                ToastUtils.showShort(getString(R.string.request_error));
                            }
                        }

                        @Override
                        public void onTimeout(Map<String, Object> request) {
                            hideProgress();
                            ToastUtils.showShort(getString(R.string.request_error));
                        }
                    });
                }

            }
        }).show();
    }

    private BlogUserInfo getBlogUserInfo(long userId,final BlogInfo blogInfo,final Tiktok2Adapter.ViewHolder viewHolder){
        if (blogUserInfoHashMap.containsKey(userId)) {
            return blogUserInfoHashMap.get(userId);
        } else {
            TelegramManager.getTelegramManager().getBlogUser(this, userId, new TgResultBlock<BlogUserInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, BlogUserInfo obj) {
                    updateBlogUserInfo(obj,blogInfo,viewHolder);
                }

                @Override
                public void onTimeout(Map<String, Object> request) {

                }
            });
            return null;
        }
    }

    private void updateBlogUserInfo(BlogUserInfo blogUserInfo,final BlogInfo blogInfo,final Tiktok2Adapter.ViewHolder viewHolder){
        if (blogUserInfo == null) {
            return;
        }
        blogUserInfoHashMap.put(blogUserInfo.user_id, blogUserInfo);
        if(blogInfo==null||viewHolder==null){
            return;
        }
        if(viewHolder == mCurrentViewHolder){
            setUserView(blogInfo,viewHolder);
        }
    }

    private MessageViewModel messageViewModel;
    private void sendMedia(final Object messageInfo ,String localPah,ChatInfo chatInfo){
        if(messageViewModel==null){
            messageViewModel = new MessageViewModel();
        }
        if(messageInfo instanceof PhotoInfo){
            messageViewModel.sendRemotePhoto(chatInfo, (PhotoInfo) messageInfo, new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    hideProgress();
                    ToastUtils.showShort(getString(R.string.collection_success));
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    hideProgress();
                    ToastUtils.showShort(getString(R.string.request_error));
                }
            });
        }else if(messageInfo instanceof VideoInfo){
            messageViewModel.sendVideoMsg(chatInfo,(VideoInfo) messageInfo,new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    hideProgress();
                    ToastUtils.showShort(getString(R.string.collection_success));
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    hideProgress();
                    ToastUtils.showShort(getString(R.string.request_error));
                }
            });
        }else{
            Observable.create(new ObservableOnSubscribe<UploadMedioInfo>() {

                @Override
                public void subscribe(@NonNull ObservableEmitter<UploadMedioInfo> emitter) throws Exception {
                    if(messageInfo instanceof PhotoInfo){
                        File newFile = new CompressHelper.Builder(CircleVerticalActivity.this).setMaxWidth(1440).setMaxHeight(2880).build().compressToFile(new File(localPah));
                        emitter.onNext(UploadMedioInfo.newImage(newFile.getAbsolutePath()));
                    }else{
                        emitter.onNext(UploadMedioInfo.newVideo(CircleVerticalActivity.this,localPah));
                    }
                    emitter.onComplete();
                }
            }).subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<UploadMedioInfo>() {
                        @Override
                        public void accept(UploadMedioInfo uploadMedioInfo) throws Exception {
                            if(uploadMedioInfo.isImage){
                                GlideApp.with(CircleVerticalActivity.this)
                                        .asBitmap()
                                        .load(uploadMedioInfo.mediaPath)
                                        .into(new SimpleTarget<Bitmap>() {
                                            @Override
                                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                                messageViewModel.sendImgMsg(chatInfo,uploadMedioInfo.mediaPath,resource,resource.getWidth(),resource.getHeight());
                                            }
                                        });
                            }else{
                                messageViewModel.sendVideoMsg(chatInfo,uploadMedioInfo.mediaPath,uploadMedioInfo.duration,uploadMedioInfo.width,uploadMedioInfo.height);
                            }
                            hideProgress();
                            ToastUtils.showShort(getString(R.string.collection_success));

                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            hideProgress();
                            ToastUtils.showShort(getString(R.string.request_error));
                        }
                    });
        }

    }



    @Override
    public void onTgEvent(TgEvent tg_event) {
        if (tg_event == null) {
            return;
        }
        switch (tg_event.event) {
            case ECircle_Like_Update:
                if(tg_event.data!=null){
                    if(tg_event.data instanceof BlogInfo){
                        BlogInfo blogInfo = (BlogInfo) tg_event.data;
                        for(int i = 0; i<mVideoList.size();i++){
                            BlogInfo current = mVideoList.get(i);
                            if(current.id == blogInfo.id){
                                current.like_count = blogInfo.like_count;
                                current.liked = blogInfo.liked;

                                if(mCurrentBlogInfo!=null&&mCurrentBlogInfo.id == blogInfo.id){
                                    if(mCurrentViewHolder!=null){
                                        mCurrentViewHolder.mTikTokView.setData(blogInfo,mBlogIndexs.get(mCurrentViewHolder.mPosition));
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
                break;
            case ECircle_Follow_Update:
                if(tg_event.data!=null&&tg_event.data instanceof BlogUserInfo){
                    BlogUserInfo blogUserInfo = (BlogUserInfo) tg_event.data;
                    updateBlogUserInfo(blogUserInfo,mCurrentBlogInfo,mCurrentViewHolder);
                }
                break;
            case ECircle_Add_Reply:
                if(tg_event.data!=null&&tg_event.data instanceof BlogReplyInfo){
                    BlogReplyInfo blogReplyInfo = (BlogReplyInfo) tg_event.data;
                    if (blogReplyInfo == null || blogReplyInfo.blog_id == null) {
                        return;
                    }
                    for(int i = 0; i<mVideoList.size();i++){
                        BlogInfo current = mVideoList.get(i);
                        if(current.id == blogReplyInfo.blog_id.blog_id){
                            current.reply_count = current.reply_count + 1;
                            if(mCurrentBlogInfo!=null&&mCurrentBlogInfo.id ==  blogReplyInfo.blog_id.blog_id){
                                if(mCurrentViewHolder!=null){
                                    mCurrentViewHolder.mTikTokView.setData(current,mBlogIndexs.get(mCurrentViewHolder.mPosition));
                                }
                            }
                            EventBus.getDefault().post(new RefreshBlogEvent());
                            break;
                        }
                    }
                }
                break;
            case EUser_Td_Contact_Photo_Ok:
            case EUser_Td_UpdateContactInfo:
                if ((tg_event.data instanceof UserInfo)) {
                    UserInfo userInfo = (UserInfo) tg_event.data;
                    if(mCurrentBlogInfo!=null&&mCurrentViewHolder!=null&&mCurrentBlogInfo.user_id == userInfo.id){
                        mCurrentViewHolder.mTikTokView.setData(mCurrentBlogInfo,mBlogIndexs.get(mCurrentViewHolder.mPosition));
                    }
                }
            case EUser_Td_Message_Photo_Ok:
            case EUser_Td_Message_Video_Ok:
                if(tg_event.data instanceof FileTaskInfo &&tg_event.dataEx instanceof FileInfo){
                    FileInfo fileInfo = (FileInfo) tg_event.dataEx;
                    String ids = ((FileTaskInfo)tg_event.data).id;
                    if(!TextUtils.isEmpty(ids)&&ids.contains("_")) {
                        String[] idArray = ids.split("_");
                        if(idArray.length > 1){
                            for(int i = 0; i<mVideoList.size();i++){
                                BlogInfo blogInfo = mVideoList.get(i);
                                boolean isVideoDownedd = blogInfo.isVideoDownloadEnough();
                                if(idArray[1].equals(String.valueOf(blogInfo.id))){
                                    switch (tg_event.event) {
                                        case EUser_Td_Message_Photo_Ok:
                                            blogInfo.updatePhotoFile(fileInfo);
                                            break;
                                        case EUser_Td_Message_Video_Ok:
                                            blogInfo.updateVideoFile(fileInfo);
                                            break;
                                    }
                                    if(tg_event.event == TelegramManager.EUser_TgEvent.EUser_Td_Message_Video_Ok&&isVideoDownedd){
                                        if(mCurrentBlogInfo!=null&&mCurrentViewHolder!=null&&mCurrentBlogInfo.id == blogInfo.id){
                                            startPlay(mCurrentViewHolder.mPosition);
                                        }
                                        return;
                                    }
                                    if(mCurrentBlogInfo!=null&&mCurrentBlogInfo.id == blogInfo.id){
                                        if(mCurrentViewHolder!=null){
                                            mCurrentViewHolder.mTikTokView.setData(blogInfo,mBlogIndexs.get(mCurrentViewHolder.mPosition));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                break;


        }
    }

    @Override
    public void setStatusBar() {
        BarUtils.setStatusBarLightMode(this, false);
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT);
    }

    @Override
    protected boolean isHaveEventBus() {
        return true;
    }

    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_circle_vertical;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mVideoView != null) {
            mVideoView.resume();
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (mVideoView != null) {
            mVideoView.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mVideoView != null) {
            mVideoView.release();
        }
    }

    @Override
    public void onBackPressed() {
        if (mVideoView == null || !mVideoView.onBackPressed()) {
            super.onBackPressed();
        }
    }
}
